import { createContext, useContext } from 'react'
import styled from 'styled-components'

const _StyledTable = styled.div`
  border: 1px solid var(--color-grey-200);

  font-size: 1.4rem;
  background-color: var(--color-grey-0);
  border-radius: 7px;
  overflow: hidden;
`

const CommonRow = styled.div`
  display: grid;
  grid-template-columns: ${(props) => props.columns};
  column-gap: 2.4rem;
  align-items: center;
  transition: none;
`

const _StyledHeader = styled(CommonRow)`
  padding: 1.6rem 2.4rem;

  background-color: var(--color-grey-50);
  border-bottom: 1px solid var(--color-grey-100);
  text-transform: uppercase;
  letter-spacing: 0.4px;
  font-weight: 600;
  color: var(--color-grey-600);
`

const _StyledRow = styled(CommonRow)`
  padding: 1.2rem 2.4rem;
  border: 1px solid var(--color-grey-200);
  font-size: 1.4rem;
  background-color: var(--color-grey-0);
  border-radius: 7px;
  overflow: hidden;

  &:not(:last-child) {
    border-bottom: 1px solid var(--color-grey-100);
  }
`

const _StyledBody = styled.section`
  margin: 0.4rem 0;
`

const _Footer = styled.footer`
  background-color: var(--color-grey-50);
  display: flex;
  justify-content: center;
  padding: 1.2rem;

  /* This will hide the footer when it contains no child elements. Possible thanks to the parent selector :has 🎉 */
  &:not(:has(*)) {
    display: none;
  }
`

const _Empty = styled.p`
  font-size: 1.6rem;
  font-weight: 500;
  text-align: center;
  margin: 2.4rem;
`

const TableContext = createContext()

function Table({ columns, children }) {
	return (
		<TableContext.Provider value={{ columns }}>
			<_StyledTable role='table'>{children}</_StyledTable>
		</TableContext.Provider>
	)
}

function Header({ children }) {
	const { columns } = useContext(TableContext)
	return (
		<_StyledHeader role='row' columns={columns}>
			{children}
		</_StyledHeader>
	)
}

function Row({ children }) {
	const { columns } = useContext(TableContext)
	return (
		<_StyledRow columns={columns} role='row'>
			{children}
		</_StyledRow>
	)
}

function Body({ render, data }) {
	if (!data.length) {
		return <_Empty>No data</_Empty>
	}
	return <_StyledBody>{data.map(render)}</_StyledBody>
}

function Footer({ children }) {
	return <_Footer role='rowgroup'>{children}</_Footer>
}

Table.Row = Row
Table.Body = Body
Table.Header = Header
Table.Footer = Footer

export default Table
